/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package inferenceEngine.types;

import inferenceEngine.labels.Label;
import inferenceEngine.labels.LabelManager;

import java.util.ArrayList;
import java.util.List;

import org.dom4j.Element;


/**
 * Inference rules
 * @author Boshi Li
 */
public class Inference {
	
	//if branch
	private Label condition = null;
	//then branch
	private ArrayList<Label> results = new ArrayList<Label>();
	private LabelManager generator =new LabelManager();
    
	public Inference( Element e ){
		setCondition(new Label( e.element("if").attribute("label").getValue() ));
		@SuppressWarnings("unchecked")
		List<Element> results =  e.elements("then") ;
		for( Element ele : results ){
			String name = ele.attribute("label").getValue();
			boolean recommended = false;
			if( ele.attribute("recommended")!=null ){
				recommended = Boolean.parseBoolean( ele.attribute("recommended").getValue() );
			}
			Label label =generator.generate(name);
			label.setRecommended(recommended);
			this.results.add( label );
		}
	}
	
	/**
	 * file the rules
	 * @return the labels in then branch
	 */
	public ArrayList<Label> fire(){
		return results;
	}
	
	/**
	 * @return if the rule can be fired
	 */
	public boolean match( Label label ){
		return label.equals( getCondition() );
	}
	
	@Override
	public int hashCode(){
		return getCondition().hashCode();
	}
	
	@Override
	public String toString(){
		StringBuilder sb = new StringBuilder();
		for( Label label : results ){
			sb.append( label );
			if( label.isRecommended() ){
				sb.append("[recommended]");
			}
			sb.append( ", " );
		}
		return String.format("if require %s, then require %s", condition, sb.toString() );
	}

	public Label getCondition() {
		return condition;
	}

	public void setCondition(Label condition) {
		this.condition = condition;
	}
	
	
}
